package com.j4cf.common.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

/**
 * @Description: 固定长度校验
 * @Author: LongRou
 * @CreateDate: 2018-05-09 19:13
 * @Version: 1.0
 **/
public class FixedLengthValidator extends ValidatorHandler<String> implements Validator<String> {

    private int length;

    private String fieldName;

    public FixedLengthValidator(int length, String fieldName) {
        this.length = length;
        this.fieldName = fieldName;
    }

    @Override
    public boolean validate(ValidatorContext context, String s) {
        if (null == s || s.length() != length) {
            context.addError(ValidationError.create(String.format("%s长度必须是%s位！", fieldName, length))
                    .setErrorCode(-1)
                    .setField(fieldName)
                    .setInvalidValue(s));
            return false;
        }
        return true;
    }

}